# 火车运输
# 2025/6/14

def max_weight(a: int, b: int, weights: list[int]):
    dp = [[0] * (a + 1) for _ in range(b + 1)]
    max_w = a + b

    for weight in weights:
        for i in range(b, -1, -1):
            for j in range(a, -1, -1):
                if weight > i and weight > j:
                    break
                elif weight <= i and weight <= j:  # 两个车厢都可以放下
                    dp[i][j] = max(dp[i - weight][j] + weight, dp[i][j - weight] + weight, dp[i][j])
                elif weight <= i:
                    dp[i][j] = max(dp[i - weight][j] + weight, dp[i][j])
                elif weight <= j:
                    dp[i][j] = max(dp[i][j - weight] + weight, dp[i][j])
                if dp[i][j] == max_w:
                    return max_w
    return dp[b][a]


if __name__ == '__main__':
    print(max_weight(10, 8, [8, 9, 1]))  # 18
